package cn.tedu.supermarket.service;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class GoodsImagesService {
    private String paths;
    public String getPaths() { return paths; }


    public int addGoodsImages(MultipartFile file) {
        System.out.println("上传开始");
        int a=0;
        String fileName = file.getOriginalFilename();
        String suffix = "";
        int beginIndex = fileName.lastIndexOf(".");
        if(beginIndex > 0){
            suffix = fileName.substring(beginIndex);
        }
        System.out.println(suffix);
        //得到唯一的文件名
        fileName =  System.currentTimeMillis()+"-"+System.nanoTime()+suffix;
//        fileName = UUID.randomUUID()+suffix;
        System.out.println(fileName);
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        String time = sdf.format(date);

        String filePath = "/home/soft01/static/file/"+time+"/";//需要修改处
        
        String path = filePath+fileName;
        paths = "/static/file/"+time+"/"+fileName;
        File targetFile = new File(filePath);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        try (FileOutputStream out = new FileOutputStream(path)){
            out.write(file.getBytes());
            out.flush();
            a = 1;
        } catch (Exception e) {
            e.printStackTrace();
            a = 0;
        }
        return a;
    }
}
